import {nanoid} from 'nanoid'

export default {
  namespaced:true,
  state: {
    todos: JSON.parse(localStorage.getItem('todos')) || [],
    activeclass: {
      activespan: false
    },
  },
  actions: {
    receive(context, value) {
      // console.log(context, value);
      const obj = { key: nanoid(), value: value, isdone: false }
      context.commit('ADD_TODO', obj);
    },
    deltodo(context, value) {
      // console.log(context, value);
      context.commit('DEL_TODO', value)
    }
  },
  mutations: {
    ADD_TODO(state, value) {
      // console.log(state, value);
      state.todos.unshift(value)
    },
    DEL_TODO(state, value) {
      // console.log(state, value);
      state.todos = state.todos.filter((item) => item.key != value.key)
    },
    CHANGE_CHECKED_STATUS(state, value) {
      const index = state.todos.findIndex((item) => {
        return item.key == value.key
      })

      state.todos[index].isdone = !state.todos[index].isdone
    },
    SELECT_ALL(state, flag) {
      state.todos.forEach(item => {
        item.isdone = flag;
      })
    },
    UPDATE_TODO(state, obj) {
      console.log(state, obj);
      for (let item of state.todos) {
        console.log('item :>> ', item);
        console.log('obj.key :>> ', obj.todo.key);
        if (item.key == obj.todo.key) {
          item.value = obj.value
          break
        }
      }
    }
  },
  getters: {}
}
